package com.gonsin.easycount.config;

import com.gonsin.easycount.EasyCount;
import com.gonsin.easycount.exception.EasyCountException;
import com.gonsin.easycount.plugin.impl.LocalExecutor;
import com.gonsin.easycount.service.impl.CountServiceImpl;
import com.gonsin.easycount.plugin.OuterCache;
import com.gonsin.easycount.plugin.OuterLock;
import com.gonsin.easycount.plugin.OuterNotifyExecutor;
import com.gonsin.easycount.plugin.impl.LocalRedisCache;
import com.gonsin.easycount.plugin.impl.LocalLock;

import java.util.concurrent.atomic.AtomicBoolean;

public class EasyCountBuilder {

    private OuterLock lock = new LocalLock();

    private static AtomicBoolean init = new AtomicBoolean(false);

    /**
     * 初始化锁的实现，如果不调用该方法，则使用本地已经实现的锁接口
     */
    public EasyCountBuilder initLock(OuterLock lock){
        this.lock = lock;
        return this;
    }



    private OuterCache cache = null;
    private RedisConfig cacheConfig = new RedisConfig();

    /**
     * 初始化缓存的实现，如果不调用该方法，则使用本地已经实现的缓存接口
     * @param lock
     * @return
     */
    public EasyCountBuilder initCache(OuterLock lock){
        this.lock = lock;
        return this;
    }

    /**
     * 初始化缓存时修改redis的一些参数
     * @param cacheConfig
     * @return
     */
    public EasyCountBuilder initCacheConfig(RedisConfig cacheConfig){
        this.cacheConfig = cacheConfig;
        return this;
    }

    private OuterNotifyExecutor executor = new LocalExecutor();

    /**
     * 初始化定时器的实现，如果不调用该方法，则使用本地已经实现的定时器接口
     * @param timer
     * @return
     */
    public EasyCountBuilder initExecutor(OuterNotifyExecutor timer){
        this.executor = executor;
        return this;
    }


    /**
     * 建立好依赖关系
     */
    public void build(){
        if(init.getAndSet(true)){
            return;
        }
        if(cache == null){
            cache = new LocalRedisCache(cacheConfig);
        }

        // 执行定时器
        CountServiceImpl countService = new CountServiceImpl(lock, cache);
        EasyCount.setInstance(countService);
        executor.start();
    }

}
